const logger = require('../../../logger');
const { HDPUBLIC, HDWALLET } = require('../../../CONSTANTS').WALLET_TYPES;
const processAddressList = require('./utils/processAddressList');

// This method is called as first thing by the SyncWorker.
// It's only when resolved that the Wallet will be ready (for what SyncWorker do)
// And therefore that's where we need to deal with all necessary step
// such as fetching all UTXO and previous TX.
//
// It should deal with additional addresses generated by a BIP44 Worker if
// fetching here found that we have more addresses that on starting of the sync up.
module.exports = async function initialSyncUp() {
  const self = this;
  const addrList = this.getAddressListToSync().map((addr) => addr.address);

  // Due to the events system, we need to handle the fact that we did subscribed to addresses
  // that we had received the transactions and store before
  // being able to release initialSyncUp as ready.
  // When we will move to bloomfilter, that part might be more complex.
  await processAddressList.call(this, addrList);

  // If it's a BIP44 wallet, and run of BIP44Worker are still generating addresses
  // we need to reprocess them before considering it done
  if ([HDPUBLIC, HDWALLET].includes(this.walletType)) {
    await new Promise((resolve) => {
      self.parentEvents.on('WORKER/BIP44WORKER/EXECUTED', async (event) => {
        const { payload } = event;
        if (payload.generated === 0) {
          resolve();
        }
        // BIP44Worker has generated more addresses, we need to process them too
        await processAddressList.call(
          self,
          self.getAddressListToSync().map((addr) => addr.address),
        );
      });
    });
  }

  logger.silly('SyncWorker - initialSyncUp - Fully synced');
};
